package com.zhangsheng.component;

import com.rabbitmq.client.Channel;
import com.zhangsheng.api.CommonResult;
import com.zhangsheng.client.MysqlFeignClient;
import com.zhangsheng.constant.OrderConstants;
import com.zhangsheng.entity.model.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 张晟
 * @version 1.0
 * @date 2022/11/21 16:47
 */
@Component
@Slf4j
public class RabbitReceiver {

    @Autowired
    private MysqlFeignClient mysqlFeignClient;

//    @RabbitListener(queues = {"order.queue"})
//    public void createOrder(Integer orderId , Message message , Channel channel) throws IOException {
//        log.info("消费者下单orderId：{}" , orderId);
//        long tag = message.getMessageProperties().getDeliveryTag();
//        try {
//            Thread.sleep(10000);
//            channel.basicNack(tag, false, true);
//            log.info("消费者下单超时");
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//    }
    @RabbitListener(queues = {"dlx.queue", "delay.queue"})
    public void closeOrderTimeout(Integer orderId , Message message , Channel channel) throws IOException {
        log.info("超时未支付订单的id为{}" , orderId);
        long tag = message.getMessageProperties().getDeliveryTag();
        CommonResult<Order> commonResult = mysqlFeignClient.getOrderById(orderId);
        Order order = commonResult.getData();
        if (order == null){
            channel.basicNack(tag, false, false);
            throw new RuntimeException("订单不存在");
        }
        log.info("订单信息为{}" , order);
        if (order.getIsdelete() == OrderConstants.ORDER_PAYED){
            channel.basicNack(tag, false, false);
            throw new RuntimeException("订单已支付，不能取消");
        }
        if (order.getIsdelete() == OrderConstants.ORDER_CANCELED){
            channel.basicNack(tag, false, false);
            throw new RuntimeException("订单已取消，请不要重复操作");
        }
        CommonResult<Boolean> result = mysqlFeignClient.closeOrder(order);
        if (result.getData()){
            log.info("消费成功手动删除消息");
            channel.basicAck(tag , false);
        }else{
            channel.basicNack(tag, false, true);
            log.info("消息未成功消费，取消订单失败");
        }
    }

}
